package com.leetcode.listnode.demo4;

/**
 * @Author Zan
 * @Create 2024/5/13 16:15
 * @ClassName: Test
 * @Description : https://leetcode.cn/problems/swap-nodes-in-pairs/   两两交换链表中的节点
 */
public class Test {
    public static void main(String[] args) {

    }
}

class Solution {
    public ListNode swapPairs(ListNode head) {
        if (head == null) {
            return head;
        }
        // 使用头节点
        ListNode dummy = new ListNode();
        dummy.next = head;
        // 直接进行交换即可
        ListNode current = dummy;
        while (current.next != null && current.next.next != null) {
            ListNode temp = current.next.next.next;
            ListNode firstnode = current.next;
            ListNode secondnode = current.next.next;
            current.next = secondnode;       // 步骤一
            secondnode.next = firstnode; // 步骤二
            firstnode.next = temp;      // 步骤三
            current = firstnode; // cur移动，准备下一轮交换
        }
        return dummy.next;
    }
}

class ListNode {
    int val;
    ListNode next;

    public ListNode() {
    }
    public ListNode(int val) {
        this.val = val;
    }
    public ListNode(int val, ListNode next) {
        this.val = val;
        this.next = next;
    }
}
